package com.haoxuer.discover.oauth.impl;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.haoxuer.discover.oauth.api.OauthHandler;
import com.haoxuer.discover.oauth.domain.GiteeUser;
import com.haoxuer.discover.oauth.domain.OauthResponse;
import com.haoxuer.discover.oauth.domain.TokenResponse;
import jodd.http.HttpRequest;

public class GiteeHandler implements OauthHandler {

  private String client_id;

  private String client_secret;

  @Override
  public void setKey(String key) {
    this.client_id = key;
  }

  @Override
  public void setSecret(String secret) {
    this.client_secret = secret;
  }

  @Override
  public OauthResponse login(String accessToken, String openid) {
    HttpRequest request = HttpRequest.get("http://gitee.com/api/v5/user");
    request.query("access_token", accessToken);
    String body = "";
    try {
      body = request.send().body();
    } catch (Exception e) {
      e.printStackTrace();
    }
    Gson gson = new Gson();
    GiteeUser user = gson.fromJson(body, GiteeUser.class);
    return user;
  }

  @Override
  public TokenResponse getToken(String code) {
    TokenResponse response = new TokenResponse();
    HttpRequest request = HttpRequest.post("https://gitee.com/oauth/token");
    request.form("client_id", client_id);
    request.form("client_secret", client_secret);
    request.form("grant_type", "authorization_code");
    // con.data("redirect_uri", "http://www.yichisancun.com/");
    request.form("code", code);
    try {
      String body = request.send().body();
      JsonParser parser = new JsonParser();
      JsonElement element = parser.parse(body);
      response.setAccessToken(ElementUtils.getString(element, "access_token"));
      response.setRefreshToken(ElementUtils.getString(element, "refresh_token"));
      response.setTokenType(ElementUtils.getString(element, "token_type"));
      response.setExpiresIn(ElementUtils.getInt(element, "expires_in"));
      response.setScope(ElementUtils.getString(element, "scope"));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return response;
  }
}
